import React from 'react'
import { success, error, info, Link, Toast, Input, Checkbox } from '../ui-components'
import { Button } from 'sq-ui';
import style from './style'
import { connect } from 'react-redux'
import util from '../util'
import rule from '../libs/rule'

class SetPassword extends React.Component {

  state = {
    password: ''
  }

  static contextTypes = {
    router: React.PropTypes.object
  }

  validate() {
    return this.props.validate(['password'], this)
  }

  handleSubmit() {
    const { password } = this.state
    if (this.validate()) return

    const cb = () => {
      this.context.router.push('/login')
      const ok = '设置密码成功, 请登录!'
      success(ok)
      util.setMessage(ok)
    }

    if (this.props.location.pathname === '/init-password') {
      this.props.initPassword(password, cb)
    } else {
      let query = this.props.location.query;
      if (query && query.uuid) {
        this.props.setPassword({ password, uuid: query.uuid }, cb);
      } else {
        this.props.setPassword(password, cb);
      }
    }
  }

  render() {
    return (
      <div>
        <div className={style.form}>
          <h2 className={style.title}>设置您的新密码</h2>
          <div className={style.input}>
            <input
              ref="password"
              autoComplete="off"
              type="password"
              placeholder={rule.password.msg}
              value={this.state.password}
              onChange={e => this.setState({ password: e.target.value.trim() })}
            />
          </div>
          <Button blue className={style.button} onClick={::this.handleSubmit} label="确定" />
        </div>
      </div>
    )
  }
}

export default SetPassword
